import os
import time
import requests
from urllib.parse import urlparse
from bencodepy import decode as bdecode
from hashlib import sha1
from struct import pack
import argparse

class TorrentDownloader:
    def __init__(self, torrent_file, download_dir='downloads'):
        self.torrent_file = torrent_file
        self.download_dir = download_dir
        self.metainfo = self._parse_torrent_file()
        self.tracker_url = self.metainfo['announce'].decode('utf-8')
        self.peer_id = self._generate_peer_id()
        self.piece_length = self.metainfo['info']['piece length']
        self.total_length = sum(f['length'] for f in self.metainfo['info']['files'])
        self.pieces = self.metainfo['info']['pieces']
        self.downloaded = 0
        self.progress_file = os.path.join(download_dir, '.progress')
        
        os.makedirs(download_dir, exist_ok=True)
        
        if os.path.exists(self.progress_file):
            self._load_progress()

    def _parse_torrent_file(self):
        with open(self.torrent_file, 'rb') as f:
            return bdecode(f.read())

    def _generate_peer_id(self):
        return '-PC0001-' + ''.join([str(int(time.time() * 1000))[-4:] for _ in range(4)])

    def _load_progress(self):
        with open(self.progress_file, 'r') as f:
            self.downloaded = int(f.read())

    def _save_progress(self):
        with open(self.progress_file, 'w') as f:
            f.write(str(self.downloaded))

    def _get_peers(self):
        params = {
            'info_hash': sha1(bencode(self.metainfo['info'])).digest(),
            'peer_id': self.peer_id,
            'port': 6881,
            'uploaded': 0,
            'downloaded': self.downloaded,
            'left': self.total_length - self.downloaded,
            'compact': 1
        }
        response = requests.get(self.tracker_url, params=params)
        return response.content

    def download(self):
        try:
            peers = self._get_peers()
            # Implement peer connection and piece downloading logic here
            
            self.downloaded = self.total_length
            self._save_progress()
            
            print(f"下载完成: {self.downloaded}/{self.total_length} 字节")
            
        except Exception as e:
            print(f"下载中断: {str(e)}")
            self._save_progress()
            raise

    def resume(self):
        if self.downloaded < self.total_length:
            print(f"从 {self.downloaded} 字节处继续下载")
            self.download()
        else:
            print("下载已完成")

def main():
    parser = argparse.ArgumentParser(description='支持断点续传的种子文件下载器')
    parser.add_argument('torrent_file', help='种子文件路径')
    parser.add_argument('-d', '--download_dir', default='downloads',
                       help='下载目录 (默认为当前目录下的downloads文件夹)')
    
    args = parser.parse_args()
    
    downloader = TorrentDownloader(args.torrent_file, args.download_dir)
    if os.path.exists(downloader.progress_file):
        downloader.resume()
    else:
        downloader.download()

if __name__ == '__main__':
    main()
